package com.toivan.mt.adapter;

import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.hwangjr.rxbus.RxBus;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.listener.DownloadListener2;
import com.toivan.mt.R;
import com.toivan.mt.fragment.MtGreenScreenFragment;
import com.toivan.mt.model.MtGreenScreen;
import com.toivan.mt.model.RxBusAction;
import com.toivan.mt.utils.MtSharedPreferences;
import com.toivan.sdk.MtSDK;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName MtGreenScreenAdapter
 * @Description 绿幕的列表适配器
 * @Author Heze 14
 * @Date 2021/6/22 11:48
 */
public class MtGreenScreenAdapter extends RecyclerView.Adapter<MtGreenScreenAdapter.MtGreenScreenViewHolder> {


    private int selectedPosition = MtSharedPreferences.getInstance().getGreenScreenPosition();

    private final Handler handler = new Handler();

    private final List<MtGreenScreen> list;

    private final MtGreenScreenFragment.GreenScreenClick greenScreenClick;

    private final Map<String, String> downloadinggreenScreen = new ConcurrentHashMap<>();

    public MtGreenScreenAdapter(List<MtGreenScreen> list, MtGreenScreenFragment.GreenScreenClick click) {
        this.list = list;
        this.greenScreenClick = click;
    }

    @NonNull
    @Override
    public MtGreenScreenViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int position) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_mt_sticker, parent, false);
        return new MtGreenScreenViewHolder(view);
    }

    @Override
    public void onBindViewHolder
        (@NonNull final MtGreenScreenAdapter.MtGreenScreenViewHolder holder,
         int position) {

        final MtGreenScreen greenScreen = list.get(holder.getAdapterPosition());

        holder.itemView.setSelected(selectedPosition == position);

        if (holder.getAdapterPosition() == 0) {
            Glide.with(holder.itemView.getContext())
                .load(R.drawable.icon_add_green_screen)
                .into(holder.thumbIV);
        } else if (greenScreen.isFromDisk()) {
            //来自硬盘的直接加载本体图片
            Glide.with(holder.itemView.getContext())
                .load(new File(greenScreen.getDir()))
                .into(holder.thumbIV);

        } else {
            //显示封面
            Glide.with(holder.itemView.getContext())
                .load(list.get(position).getThumb())
                .into(holder.thumbIV);
        }

        //判断是否已经下载
        if (greenScreen.getDownloaded()) {
            holder.downloadIV.setVisibility(View.GONE);
            holder.loadingIV.setVisibility(View.GONE);
            holder.stopLoadingAnimation();
        } else {
            //判断是否正在下载，如果正在下载，则显示加载动画
            if (downloadinggreenScreen.containsKey(greenScreen.getName())) {
                holder.downloadIV.setVisibility(View.GONE);
                holder.loadingIV.setVisibility(View.VISIBLE);
                holder.startLoadingAnimation();
            } else {
                holder.downloadIV.setVisibility(View.VISIBLE);
                holder.loadingIV.setVisibility(View.GONE);
                holder.stopLoadingAnimation();
            }
        }

        if (greenScreen.isFromDisk()) {

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MtSDK.get().setGreenScreenName(greenScreen.getName());
                    MtSharedPreferences.getInstance().setGreenScreenName(greenScreen.getName(), holder.getAdapterPosition());
                    int lastPosition = selectedPosition;
                    selectedPosition = holder.getAdapterPosition();
                    notifyItemChanged(selectedPosition);
                    notifyItemChanged(lastPosition);
                    RxBus.get().post(RxBusAction.ACTION_SELECT_GREEN_SCREEN, "");
                }
            });

            return;
        }

        holder.itemView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                if (holder.getAdapterPosition() == 0) {
                    greenScreenClick.clickGreenScreenFromDisk();
                    return;
                }

                if (!greenScreen.getDownloaded()) {
                    //未下载

                    //如果已经在下载了，则不操作
                    if (downloadinggreenScreen.containsKey(greenScreen.getName())) {
                        return;
                    }
                    new DownloadTask.Builder(greenScreen.getUrl(), new File(MtSDK.get().getGreenScreenPath()))
                        .setMinIntervalMillisCallbackProcess(30)
                        .setConnectionCount(1)
                        .build()
                        .enqueue(new DownloadListener2() {
                            @Override public void taskStart(@NonNull DownloadTask task) {
                                downloadinggreenScreen.put(greenScreen.getName(), greenScreen.getUrl());
                                handler.post(new Runnable() {
                                    @Override public void run() {
                                        notifyDataSetChanged();
                                    }
                                });
                            }


                            @Override public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable final Exception realCause) {
                                if (cause == EndCause.COMPLETED) {
                                    downloadinggreenScreen.remove(greenScreen.getName());
                                    File file = new File(MtSDK.get().getGreenScreenPath(), greenScreen.getName() + ".png");
                                    task.getFile().renameTo(file);
                                    greenScreen.setDownloaded(true);
                                    greenScreen.greenScreenDownload(holder.itemView.getContext());
                                    handler.post(new Runnable() {
                                        @Override public void run() {
                                            notifyDataSetChanged();
                                        }
                                    });
                                } else {
                                    //退出队列
                                    downloadinggreenScreen.remove(greenScreen.getName());
                                    //弹出toast提示
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            notifyDataSetChanged();
                                            if (realCause != null) {
                                                Toast.makeText(holder.itemView.getContext(), realCause.getMessage(), Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                }
                            }
                        });

                } else {
                    //已下载
                    if (holder.getAdapterPosition() == RecyclerView.NO_POSITION) {
                        return;
                    }

                    MtSDK.get().setGreenScreenName(greenScreen.getName());
                    MtSharedPreferences.getInstance().setGreenScreenName(greenScreen.getName(), holder.getAdapterPosition());
                    int lastPosition = selectedPosition;
                    selectedPosition = holder.getAdapterPosition();
                    notifyItemChanged(selectedPosition);
                    notifyItemChanged(lastPosition);

                    RxBus.get().post(RxBusAction.ACTION_ENABLE_CANCEL, "");
                    RxBus.get().post(RxBusAction.ACTION_SELECT_GREEN_SCREEN, "");
                }

            }
        });

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    class MtGreenScreenViewHolder extends RecyclerView.ViewHolder {
        public ImageView thumbIV, downloadIV, loadingIV;

        public MtGreenScreenViewHolder(@NonNull View itemView) {
            super(itemView);
            thumbIV = itemView.findViewById(R.id.thumbIV);
            downloadIV = itemView.findViewById(R.id.downloadIV);
            loadingIV = itemView.findViewById(R.id.loadingIV);
        }


        public void startLoadingAnimation() {
            Animation animation = AnimationUtils.loadAnimation(itemView.getContext(), R.anim.loading_animation);
            loadingIV.startAnimation(animation);
        }


        public void stopLoadingAnimation() {
            loadingIV.clearAnimation();
        }
    }

    public void cancelSelected() {
        selectedPosition = -1;
        MtSDK.get().setGreenScreenName("");
        MtSharedPreferences.getInstance().setGreenScreenName("", selectedPosition);
        notifyDataSetChanged();
    }

    @Override
    public long getItemId(int position) {
        return String2Hash(list.get(position).getName());
    }

    /**
     * 用于对String进行简单Hash
     *
     * @param key 被Hash的对象
     * @return int类型的Hash值
     */
    private int String2Hash(String key) {
        int arraySize = 11113;            //数组大小一般取质数
        int hashCode = 0;
        for (int i = 0; i < key.length(); i++) {        //从字符串的左边开始计算
            int letterValue = key.charAt(i) - 96;//将获取到的字符串转换成数字，比如a的码值是97，则97-96=1 就代表a的值，同理b=2；
            hashCode = ((hashCode << 5) + letterValue) % arraySize;//防止编码溢出，对每步结果都进行取模运算
        }
        return hashCode;
    }

    public void syncNotifyDataChanged() {
        this.selectedPosition = -1;
        notifyDataSetChanged();
    }

    public void selectItem(int selectedPosition) {
        this.selectedPosition = selectedPosition;
        MtSDK.get().setGreenScreenName(list.get(selectedPosition).getName());
        MtSharedPreferences.getInstance().setGreenScreenName(list.get(selectedPosition).getName(), selectedPosition);
        RxBus.get().post(RxBusAction.ACTION_SELECT_GREEN_SCREEN, "");
    }

}
